# -*- coding: utf-8 -*- 
"""
Created by hcx on 17-7-21 上午9:17.
@author: 胡超翔
"""
from __future__ import absolute_import
from __future__ import unicode_literals

import logging

from autodeploy.apps.operation.views import create_log

logger = logging.getLogger(__name__)


# def use_ansible(server_list, group_name='all', playbooks=None, variable=None, ):
#     """
#
#     :param server_list: 服务器列表
#     :param group_name:用户组名
#     :param playbooks:剧本路径
#     :param variable:剧本内的变量，以字典方式传入，例如:若variable={'item':item}:
#             ---
#             -host:xxx
#             -task:
#                 -name:{{item}}
#     :return:
#     """
#     result = {'status': [], 'msg': {}}
#     logger.info('运行开始*********************************************')
#     for i in range(len(server_list)):
#         server = server_list[i]
#         if not playbooks:
#             playbooks = MEDIA_ROOT + '/task/information.yaml'
#             ansible = AnsibleTask([server_list[i].ip], [playbooks], user=server_list[i].ssh_user,
#                                   password=server_list[i].ssh_password, group_name=group_name,
#                                   variable=variable)
#             status, msg = ansible.run()
#         else:
#             ansible = AnsibleTask([server_list[i].ip], [playbooks.path], user=server_list[i].ssh_user,
#                                   password=server_list[i].ssh_password, group_name=group_name,
#                                   variable=variable)
#             status, msg = ansible.run()
#
#         result['status'].append(status)
#         result['msg'] = msg
#         print msg
#         logger.info(msg)
#         # 根据剧本执行结果，创建记录
#         if msg['success']['ok'] or msg['success']['change'] or msg['success']['fact']:
#
#             if msg['success']['ok']:
#                 create_log(server, content=playbooks, result=str(msg['success']['ok']), status='success')
#             if msg['success']['change']:
#                 if playbooks == MEDIA_ROOT + '/task/information.yaml':
#                     change_msg(server, msg['success']['change'], playbooks=playbooks, status='information')
#                 else:
#                     change_msg(server, msg['success']['change'], playbooks=playbooks)
#             if msg['success']['fact']:
#                 re = ''
#                 if playbooks == MEDIA_ROOT + '/task/information.yaml':
#                     if msg['success']['fact']:
#                         # 获取硬件信息时
#                         re = fact_msg(server, msg['success']['fact'])
#                 if re:
#                     create_log(server, content=playbooks, result=re, status='success')
#                 else:
#                     if len(msg['success']['fact']) > 1000:
#                         re = "数据太长无法存入数据库"
#                     else:
#                         re = msg['success']['fact']
#                     create_log(server, content=playbooks, result=re, status='success')
#         elif msg['fatal']:
#             create_log(server, content=playbooks, result=str(msg['fatal']), status='defeat')
#             logger.error('剧本运行失败,错误提示:%s' % msg['fatal'])
#         elif msg['unreachable']:
#             create_log(server, content=playbooks, result=str(msg['unreachable']), status='defeat')
#             logger.error('剧本运行失败,错误提示:%s' % msg['unreachable'])
#         else:
#             logger.error('剧本运行结果有误')
#             create_log(server, content=playbooks, result='剧本运行结果有误', status='success')
#     logger.info('运行结束*********************************************')
#     return result


def fact_msg(server, fact):
    """获取用户硬件信息"""
    logger.info("get Hardware information *********")
    # 物理内存容量
    try:
        mem_total = fact["ansible_memtotal_mb"]
    except Exception as e:
        logging.error('ansible setup模块获取虚拟内容容量数据失败:%s' % e)
        mem_total = 0
    # 虚拟内容容量
    try:
        swap_total = fact["ansible_memory_mb"]["swap"]["total"]
    except Exception as e:
        logging.error('ansible setup模块获取虚拟内容容量数据失败:%s' % e)
        swap_total = 0
    # CPU型号
    try:
        cpu_type = fact['fact']["ansible_processor"][-1]
    except Exception as e:
        logging.error('ansible setup模块获取CPU型号数据失败:%s' % e)
        cpu_type = "未知"
    # CPU核心数
    try:
        cpu_total = fact["ansible_processor_vcpus"]
    except Exception as e:
        logging.error('ansible setup模块获取CPU核心数数据失败:%s' % e)
        cpu_total = 0
    # 操作系统类型
    try:
        os_type = " ".join((fact["ansible_distribution"], fact["ansible_distribution_version"]))
    except Exception as e:
        logging.error('ansible setup模块获取操作系统类型数据失败:%s' % e)
        os_type = "未知"
    # 硬盘总容量
    try:
        disk_total = sum([int(fact["ansible_devices"][i]["sectors"]) * \
                          int(fact["ansible_devices"][i]["sectorsize"]) / 1024 / 1024 / 1024 \
                          for i in fact["ansible_devices"] if i[0:2] in ("sd", "ss")])
    except Exception as e:
        logging.error('ansible setup模块获取硬盘总容量数据失败:%s' % e)
        disk_total = 0
    # 硬盘挂载名及容量
    try:
        disk_mount = str(
            [{"mount": i["mount"], "size": i["size_total"] / 1024 / 1024 / 1024} for i in fact["ansible_mounts"]])
    except Exception as e:
        logging.error('ansible setup模块获取硬盘挂载名及容量数据失败:%s' % e)
        disk_mount = "未知"
    # 服务器型号
    try:
        server_type = fact["ansible_product_name"]
    except Exception as e:
        logging.error('ansible setup模块获取服务器型号数据失败:%s' % e)
        server_type = "未知"
    # 服务器主机名
    try:
        host_name = fact["ansible_hostname"]
    except Exception as e:
        logging.error('ansible setup模块获取服务器主机名数据失败:%s' % e)
        host_name = "未知"
    # 操作系统内核型号
    try:
        os_kernel = fact["ansible_kernel"]
    except Exception as e:
        logging.error('ansible setup模块获取操作系统内核型号数据失败:%s' % e)
        os_kernel = "未知"
    # 服务器ipv4地址
    try:
        ipv4 = str(fact["ansible_all_ipv4_addresses"])
    except Exception as e:
        logging.error('ansible setup模块获取服务器ipv4地址数据失败:%s' % e)
        ipv4 = "未知"
    server.cpu_type = cpu_type
    server.cpu_total = cpu_total
    server.os_type = os_type
    server.ipv4 = ipv4
    server.disk_total = disk_total
    server.disk_mount = disk_mount
    server.host_name = host_name
    server.os_kernel = os_kernel
    server.server_type = server_type
    server.save()
    result = "%s,%s,%s,%s,%s,%s,%s,%s,%s"%(cpu_type,cpu_total,os_type,ipv4,disk_total,disk_mount,host_name,os_kernel,server_type)
    logger.info("over and success********************")
    return result


def change_msg(server, change,  status=None):
    """获取剧本运行成功的change信息"""
    if status == 'information':
        logger.info("save information保存进程信息****************")
        # 若状态为information,这确定为获取用户进程信息
        if len(str(change['stdout_lines']))<10000:
            server.process = str(change['stdout_lines'])
        else:
            server.process = str(change['stdout_lines'])[0:9999]
        server.save()
        logger.info("保存完毕****************")
    create_log(server, result=str(change), status='success')
